package com.wzh.aop.operatelog.component;

import com.wzh.aop.operatelog.annotation.OperateLog;
import com.wzh.aop.operatelog.constant.OperateModule;
import com.wzh.aop.operatelog.constant.OperateType;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @Author zh wang
 * @Create 2025/7/24 9:12
 * @Description： 操作日志切面，与业务解耦；
 */
@Aspect
@Component
public class OperateLogAspect {
    @Pointcut("@annotation(com.wzh.aop.operatelog.annotation.OperateLog)")
    public void aspect() {
    }

    @Around("aspect()")
    public Object aroundAdvice(ProceedingJoinPoint point) throws Throwable {
        // ---- 获取类方法信息 ----
        Enum[] enumArr = new Enum[2];
        // 获取类名
        //String className = point.getTarget().getClass().getName();
        //// 获取方法名
        //String methodName = point.getSignature().getName();
        //// 获取请求参数
        //Object[] args = point.getArgs();
        // 获取方法注解：
        //Class<?> targetClass = Class.forName(className);
        //Method[] methods = targetClass.getMethods();
        //for (Method method : methods) {
        //    if (StringUtils.equals(methodName, method.getName())) {
        //        Class<?>[] parameterTypes = method.getParameterTypes();
        //        if (parameterTypes.length == args.length) {
        //            // 获取方法注解
        //            OperateLog operateLog = method.getAnnotation(OperateLog.class);
        //            if (operateLog != null) {
        //                // 获取注解信息
        //                enumArr[0] = operateLog.operateType();
        //                enumArr[1] = operateLog.operateModule();
        //            }
        //        }
        //    }
        //}
        // 优化方案：使用 AspectJ 提供的更精确方法 MethodSignatureImpl
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        OperateLog operateLog = method.getAnnotation(OperateLog.class);
        if (operateLog != null) {
            // 获取注解信息
            enumArr[0] = operateLog.operateType();
            enumArr[1] = operateLog.operateModule();
        }

        // ---- 方法执行前 ----
        OperateType operateType = (OperateType) enumArr[0];
        OperateModule operateModule = (OperateModule) enumArr[1];
        System.out.printf("方法执行前。operateType=%s, operateModule=%s%n", operateType, operateModule);

        // ---- 方法执行 ----
        Object proceed = point.proceed();

        // ---- 方法执行后 ----
        System.out.println("方法执行后：End..");

        return proceed;
    }
}
